import 'dart:io';

import 'package:e_reception_flutter/constants/branch/branch_test_constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/upgrade_response_bean.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class VgNetDelegate extends UpgradeNetDelegate {
  static final String ANDROID_TYPE_PARAMS = "EReception_Android";

  static final String IOS_TYPE_PARAMS = "EReception_ios";

  ///todo待修改 等待更新库错误提示完善
  final bool isShowLastestTips;

  VgNetDelegate(this.isShowLastestTips);

  static VgNetDelegate of(bool isShowLastestTips) {
    return VgNetDelegate(isShowLastestTips);
  }

  @override
  String get checkUpgradeUrl =>
     ServerApi.BASE_URL + "att/selectAPKVal?type=${getPaltformTypeStr()}";

  @override
  HttpType get httpType => HttpType.post;

  @override
  get transToUpgradeInfoFunc => (Response response) {
        print("打印请求结果：\n"
            "${response?.data}");
        if (response?.data == null) {
          return null;
        }
        VersionBean versionInfoBean =
            UpgradeResponseBean.fromMap(response?.data)?.data?.version;
        if (versionInfoBean == null) {
          return null;
        }

        ///合成升级所有参数
        UpgradeInfoBean upgradeInfoBean = UpgradeInfoBean(
          androidApkUrl: versionInfoBean?.dwurl,
          androidVersion: versionInfoBean?.val,
          iosVersion: versionInfoBean?.val,
          isAndroidForce: versionInfoBean?.isForce() ?? false,
          isIOSForce: versionInfoBean?.isForce() ?? false,
          versionName: versionInfoBean?.vername,
          updateLog: versionInfoBean?.upcontent,
          extra: versionInfoBean,
        );

        return upgradeInfoBean;
      };

  @override
  get compareMoreThanVersionFunc => (int currentBuildNumber,
          dynamic upgradeVersion, UpgradeInfoBean upgradeInfoBean) {
        if (upgradeVersion == null ||
            upgradeVersion is! int ||
            currentBuildNumber <= 0 ||
            upgradeVersion <= 0) {
          _toLatestVersion();
          return false;
        }
        if (currentBuildNumber < upgradeVersion) {
          print("当前版本号 | 升级号：$currentBuildNumber | $upgradeVersion");
          return true;
        }
        _toLatestVersion();
        return false;
      };

  void _toLatestVersion() {
    if (isShowLastestTips ?? true) {
      VgToastUtils.toast(AppMain.context, "已是最新版本");
    }
  }

  @override
  get httpLoadingFunc => () {
        VgHudUtils.show(AppMain.context, "获取版本");
      };

  @override
  get httpLoadFinishFunc => () {
        VgHudUtils.hide(AppMain.context);
      };

  @override
  String get apkFolderName => "Ereception.apk";

  ///目前测试版暂停静默下载
  @override
  bool get isWifiAutoDownload =>
      ConstantRepository.of() is BranchTestConstant ? false : true;

  @override
  get confirmIOSFunc => (UpgradeInfoBean upgradeInfoBean, VoidCallback onPop) {
        // 目前跳转到蒲公英地址
        _openBrowerDownload();
      };

  //打开外部浏览器
  _openBrowerDownload() async {
    final String iosDownloadUrl = ConstantRepository.of().getIOSDownloadUrl();
    if (iosDownloadUrl == null || iosDownloadUrl.isEmpty) {
      VgToastUtils.toast(AppMain.context, "有版本更新，请联系管理员");
      return;
    }
    if (await canLaunch(iosDownloadUrl)) {
      await launch(iosDownloadUrl);
    } else {
      throw 'Could not launch $iosDownloadUrl';
    }
  }

  String getPaltformTypeStr() {
    if (Platform.isAndroid) {
      return ANDROID_TYPE_PARAMS;
    }
    if (Platform.isIOS) {
      return IOS_TYPE_PARAMS;
    }
    return null;
  }

  ///目前测试版不读取缓存
  @override
  bool get isEnableApkCache =>
      ConstantRepository.of() is BranchTestConstant ? false : true;
}
